﻿using Beryl.OrderControllers.DataStructural;
using Beryl.OrderControllers.DBUpdate;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace Beryl.OrderControllers
{
    //转生产批次类
    public class productOrders
    {
        private static productOrders instance = null;
        private static readonly object uniqueLock = new object();

        public static productOrders Instance
        {
            get
            {
                lock (uniqueLock)
                {
                    if (instance == null)
                    {
                        instance = new productOrders();
                    }
                }
                return instance;
            }
        }
        public productOrders() { }
        public List<string> proOrderQuery(string para)
        {
            List<string> list = new List<string>();
            try
            {
                JArray jsonArr = (JArray)JsonConvert.DeserializeObject(para);
                var k = jsonArr[0];
                string cStatus = "";
                string reMakeF = "";
                string cProductDepNo = k["cProductDepNo"].ToString();
                string cStatusNo = k["cStatusNo"].ToString();
                string cReworkFlag = k["cReworkFlag"].ToString();
                string cPOrderNo = k["cPOrderNo"].ToString();
                string cMatNo = k["cMatNo"].ToString();
                string cCusName = k["cCusName"].ToString();
                string cMakeTimeS = k["cMakeTimeS"].ToString() + " 00:00:00";
                string cMakeTimeE = k["cMakeTimeE"].ToString() + " 99:99:99";
                string saleOrderNum = k["saleOrderNum"].ToString();
                switch(cStatusNo)
                {
                    case "All":
                        cStatus = "0001";
                        break;
                    case "已物料需求":
                        cStatus = "0032";
                        break;
                    case "已转生产批次":
                        cStatus = "0050";
                        break;
                    case "已打印":
                        cStatus = "0051";
                        break;
                    case "生产中":
                        cStatus = "0080";
                        break;
                }

                switch(cReworkFlag)
                {
                    case "All":
                        reMakeF = "2";
                        break;
                    case "重工单":
                        reMakeF = "1";
                        break;
                    case "非重工单":
                        reMakeF = "0";
                        break;
                }

                string sql = string.Format(@"SELECT 
                a.cPOrderNo,
                a.cStatusNo,
                c.cStatusDesc,
                c.cNextStatusDesc,
                a.cStaUpdateTime,
                a.cMatNo,
                a.dPlanQty,
                a.cProductDepNo,
                a.cCusName,
                b.cProductDepName,
                a.cPOTypeNo,
                a.cPOTypeName,
                a.dDeliveryDate,
                a.dProBatch,
                a.MotypeCode,
                a.Description,
                a.cMakeTime,
                b.cSpecifucation,
				d.cSourceNo,
                f.cParentSONo,
				ISNULL(CONVERT(decimal,dQty),0) as dQty,
                CASE WHEN  a.cReworkFlag = 1 THEN '重工单' 
                     ELSE '非重工单' 
                END AS cReworkFlag
                FROM 
                    APS_PlanOrder a 
                    LEFT join APS_OrderStatus c ON a.cStatusNo = c.cStatusNo
					LEFT join APS_PlanOandSaleORelat d on a.cPOrderNo = d.cPOrderNo
					LEFT join APS_SOrder f on d.cSourceNo = f.cSONo
                    LEFT JOIN APS_MatData_V b ON a.cMatNo = b.cMatNo
                where a.cProductDepNo = '{0}' ", cProductDepNo);

                if(cStatus != "0001")
                {
                    sql = sql + " and a.cStatusNo = '" + cStatus + "' ";
                }
                if(reMakeF != "2")
                {
                    sql = sql + " and a.cReworkFlag = '" + reMakeF + "' ";
                }
                if (cPOrderNo != "")
                {
                    sql = sql + " and a.cPOrderNo = '" + cPOrderNo + "' ";
                }
                if (cMatNo != "")
                {
                    sql = sql + " and a.cMatNo = '" + cMatNo + "' ";
                }
                if (cCusName != "")
                {
                    sql = sql + " and a.cCusName like '%" + cCusName + "%' ";
                }
                if (cMakeTimeS != "")
                {
                    sql = sql + " and a.cMakeTime >= '" + cMakeTimeS + "' ";
                }
                if (cMakeTimeE != "")
                {
                    sql = sql + " and a.cMakeTime <= '" + cMakeTimeE + "' ";
                }

                if(saleOrderNum != "")
                {
                    sql = sql + " and f.cParentSONo like '%" + saleOrderNum + "%' ";
                }
                sql += "ORDER BY cPOrderNo DESC";

                string strPicYZ = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if(strPicYZ.Equals("[]"))
                {
                    throw new Exception("数据为空");
                }
                list.Add(strPicYZ);
            }
            catch(Exception e)
            {
                list.Add(e.Message);
            }
            return list;
        }

        //生产订单转生产批次
        public List<string> ProOrders(string para)
        {
            List<string> list = new List<string>();
            try
            {
                JArray jsonArr = (JArray)JsonConvert.DeserializeObject(para);
                var k = jsonArr[0];
                string cProductDepNo = k["cProductDepNo"].ToString();
                string cIndependentBatch = k["cIndependentBatch"].ToString();//尾数独立成批标志
                bool IndependentBatch = false;
                if (cIndependentBatch == "Checked")
                {
                    IndependentBatch = true;
                }
                string cplanOrder = k["cplanOrder"].ToString();//前端选择的生成订单
                string[] array = cplanOrder.Split(',');
                List<string> cPOrderNoArr = new List<string>();
                string cPOrderNoStr = "";
                List<string> cPOrderNoArr1 = new List<string>();
                string cPOrderNoStr1 = "";
                for (int i = 0; i < array.Length;i++)
                {
                    cPOrderNoStr += "APS_PlanOrder.cPOrderNo = '" + array[i] + "' OR ";
                    cPOrderNoStr1 += "cOrderNo = '" + array[i] + "' OR ";
                    cPOrderNoArr.Add(array[i]);
                    cPOrderNoArr1.Add(array[i]);
                }
                cPOrderNoStr = cPOrderNoStr.Substring(0, cPOrderNoStr.Length - 4);
                cPOrderNoStr1 = cPOrderNoStr1.Substring(0, cPOrderNoStr1.Length - 4);

                string cloginUser = k["cloginUser"].ToString(); //登录用户
                if (cplanOrder == "")
                {
                    throw new Exception("订单号为空");
                }
                // 从数据库读入数据
                string MatData = string.Format(@"SELECT
                        APS_MatData_V.cMatNo,
                        APS_MatData_V.cUnit,
                        APS_MatData_V.dwidth,
                        APS_MatData_V.dVoltage,
                        APS_MatData_V.Unit,
                        APS_MatData_V.cMatName,
                        APS_MatData_V.cSpecifucation,
                        APS_MatData_V.cCateNo,
                        APS_MatData_V.cCapacity,
                        APS_MatData_V.dProBatch,
                        APS_MatData_V.cProMethod
                    FROM
                        APS_MatData_V
                    WHERE
                        1 = 1;");
                var MatDataRow = CommonMethod.Instance.retData(MatData, "", "");//物料数据

                string planOrder = string.Format(@"SELECT
                            APS_PlanOrder.cPOrderNo,
                            APS_PlanOrder.cMatNo,
                            APS_PlanOrder.dPlanQty,
                            APS_PlanOrder.dPlanQty1,
                            APS_PlanOandSaleORelat.cSourceNo,
                            APS_SOrder.cParentSONo,
                            ISNULL(CONVERT(decimal,dNetQty3),0) as dQty3,
                            ISNULL(CONVERT(decimal,dNetQty2),0) as dQty2,
                            ISNULL(CONVERT(decimal,dNetQty),0) as dQty,
                            APS_PlanOrder.dDeliveryDate,
                            APS_PlanOrder.cProductDepNo,
                            APS_PlanOrder.cReworkFlag,
                            APS_SOrder.cOFlag,
                            APS_PlanOrder.cBigBegProDate,
                            APS_PlanOrder.MotypeCode,
                            APS_PlanOrder.dProBatch,
                            APS_PlanOrder.Coefficient,
                            APS_PlanOrder.putProQty
                        FROM
                            APS_PlanOrder
                            LEFT JOIN APS_PlanOandSaleORelat ON APS_PlanOandSaleORelat.cPOrderNo = APS_PlanOrder.cPOrderNo
                            LEFT JOIN APS_SOrder ON APS_SOrder.cSONo = APS_PlanOandSaleORelat.cSourceNo 
                        WHERE {0};", cPOrderNoStr);
                var planOrderRow = CommonMethod.Instance.retData(planOrder, "", "");//'未转批次'的计划订单，已关联子销售订单、销售订单

                string APS_Valid = string.Format(@"SELECT cOrderNo,cMatNo,dPlanQty,cOperationNo,cOperationName,cOpSeq,cMatandResNo,cMatandResName,cMatandResType," +
                              "dWidth,dLength,cSpecifution,cUnit,dReqQty,cCapacityLow,cCapacityUp,cCapacity,cBomid,cCateNo,dVoltage,Unit,cSortSeq  FROM APS_ValidBOM WHERE {0};", cPOrderNoStr1);
                var ValidRow = CommonMethod.Instance.retData(APS_Valid, "", "");
                var ValidBOMObj = CommonMethod.Instance.getValidBOM(ValidRow);


                CommonMethod.Instance.Global_Start();
                var manuBOM = CommonMethod.APS_ManuBOM;
                var routing = CommonMethod.APS_Routing;
                //CommonMethod.Instance.Timer_Start();
                //var ValidBOMObj = CommonMethod.VaildBom;
                //BOM数据结构化
                var BomDataObj = proOrderStructural.Instance.getBomData(manuBOM);
                //物料主数据结构化
                var MatDataObj = proOrderStructural.Instance.getMatData(MatDataRow);
                //生成订单结构化
                var planOrderObj = proOrderStructural.Instance.getPlanOrder(planOrderRow);
                //工艺路线结构化
                var RoutingObj = proOrderStructural.Instance.getRouting(routing);
                //定义生成订单和对应的子销售订单对象obj{生成订单{子销售订单[]}}
                var obj = proOrderStructural.Instance.getobj(cPOrderNoArr, planOrderRow);
                //按批次数量拆批
                var proOrderObj = proOrderStructural.Instance.getProOrder(planOrderObj, MatDataObj, IndependentBatch, obj, RoutingObj, BomDataObj, cloginUser);

                var proLotMatQtyObj = proOrderStructural.Instance.getBatchMatQty(proOrderObj, obj, ValidBOMObj); 
                var proRoutingObj = proOrderStructural.Instance.getProRouting(proLotMatQtyObj, RoutingObj);

                // 删除旧表信息
                proUpdate.Instance.deleteProLot(proOrderObj);
                // 输出写入
                proUpdate.Instance.updateProOrder(proOrderObj);
                // 更新批次物料子件总需求
                proUpdate.Instance.insertBatchMatTotalQty(proLotMatQtyObj);

                proUpdate.Instance.insertProRouting(proRoutingObj);
                list.Add("success");
            }
            catch (Exception e)
            {
                list.Add(e.Message);
            }
            return list;
        }


        //订单更新查询
        public List<string> OrderUpdateQuery(string para)
        {
            List<string> list = new List<string>();
            try
            {
                var sql = "select cSourceNo from APS_PlanOandSaleORelat where cPOrderNo= '" + para + "'";

                string strPicYZ = JsonConvert.SerializeObject(CommonMethod.Instance.selectDatabase(sql));
                if (strPicYZ.Equals("[]"))
                {
                    throw new Exception("数据为空");
                }
                list.Add(strPicYZ);
            }
            catch(Exception ex)
            {
                list.Add(ex.Message);
            }
            return list;
        }
    }
}